import { Databasetitle, Databasesort_rules, DatabaseList, DataBasetexport, filtersList } from '@/api/biomedicalArea'

import { Button, notification, Modal, Typography, Popover, InputNumber, DatePicker, TreeSelect, Descriptions, Select, Tooltip } from 'antd'

import { export_daily_counts } from '@/api/common'

import { DownloadOutlined, SearchOutlined } from '@ant-design/icons'

import { HsAdminInput, HsAdminProTable, HsAdminSpin, HsAdminTable } from '@hs-admin/base-components'

import { EMPTYTEXT, handleTableShowDate, message } from '@hs-admin/utils'

import { useImmer } from 'use-immer'

const { Text } = Typography

import { useState, useRef, useEffect, memo, forwardRef, useImperativeHandle } from 'react'

import { ServerAreaSelect, ServerEmailModal, ServerSelect, HsAdminSelecPark, ServerCascader } from '@hs-server/components'
import dayjs from 'dayjs'
import { HonorTreeData } from '@/utils/SearchTreeData'
import useShowDetail from './Detailmodule'
import { openCompanyDetail } from 'hs-react-company'
import { transformNormalNumberType } from '@hs-admin/api'

const RelationList = (props: any, ref: any) => {
  const { Inputsearch, release_item_id, release_item_name } = props

  const [searchValue, setsearchValue]: any = useState({
    release_item_id: release_item_id,
    keywords: '',
    filters: {
      pca: [],
      polymerize: [],
      date: [],
      park: [],
      time: [],
      industry: [],
      national_economy_classification: [],
      strategic_industry: [],
      qualification: [],
      number_range: []
    },
    relation: null,
    ids: null,
    sort: null
  })
  //导出提示栏
  const [api, contextHolder] = notification.useNotification()

  //勾选的Keys
  const [selectedRowKeys, setselectedRowKeys]: any = useState([])

  //列表counts
  const [counts, setcounts] = useState(0)

  //导出邮箱ref
  const EmailModalRef = useRef<any>(null)

  //导出数量超出5000 小于一万限制弹框
  const [isModalOpen2, setModalOpen2] = useState(false)

  //列表的columns
  const [columns, setColumns]: any = useState([])

  //列表数据
  const [data, setData] = useState([])

  //列表表头
  const [columnsStateMap, setColumnsStateMap]: any = useState({})

  const [columnsChangeFlag, setcolumnsChangeFlag] = useState(true)

  const [loading, setloading] = useState(true)

  //控制园区列表请求
  const [ParkList, setParkList] = useState('false')

  const { RangePicker } = DatePicker

  //获取筛选项
  const [filtersitem, setfiltersitem] = useState([])

  const actionRef: any = useRef()

  // 详情字段
  const detailFieldList = useRef<any>([])
  const { Detail, showModal: showDetailModal } = useShowDetail()

  // 查询导出数量
  const export_counts = () => {
    export_daily_counts().then((res: any) => {
      res.daily_count = res.daily_count > 0 ? 20000 - res.daily_count : 20000
      setcounts(res.daily_count)
    })
  }

  //处理options数据结构
  const Selectdata: any = (list: any, key: any, label: any) => {
    const arr: any = []
    list.map((item: any) => {
      const obj = {
        value: key ? item[key] : item,
        label: label ? item[label] : item
      }
      arr.push(obj)
    })
    return arr
  }

  // 时间筛选年月日
  const handleTimeRankonChange = (datesting: any, item: any, type: any) => {
    const obj: any = {
      name: item.name,
      type: item.type,
      config: {
        column: item.config.column,
        start: {
          show: datesting[0],
          value: datesting[0]
        },
        end: {
          show: datesting[1],
          value: datesting[1]
        }
      }
    }

    if (datesting[0]) {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = [obj, ...preValue]
        return { ...prevItems }
      })
    } else {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = preValue
        return { ...prevItems }
      })
    }
  }

  // 数据筛选组件选中的值
  const DataSelectsuccess = (e: any, item?: any) => {
    const obj: any = {
      name: item.name,
      type: item.type,
      config: {}
    }
    if (item.type !== 'true_or_false') {
      if (item.type === 'pca') {
        obj.config = {
          province_column: item.config.province_column,
          city_column: item.config.city_column,
          area_column: item.config.area_column,
          values: e
        }
      } else if (item.type === 'polymerize' || item.type === 'park' || item.type === 'qualification') {
        obj.config = {
          column: item.config.column
        }
        const logs: any = []

        //qualification 资质信息
        if (item.type === 'qualification') {
          e.map((its: any) => {
            logs.push({ show: its, value: its })
          })
        } else {
          e.map((its: any) => {
            logs.push({ show: its.label, value: its.value })
          })
        }

        obj.config.values = logs
      } else {
        obj.config = {
          // column: item.config.column, 先写死
          column: item.type === 'industry' ? 'hs_ind_list' : 'nea_ind_list',
          values: e
        }
      }
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[item.type] = obj.config.values.length ? [...preValue, obj] : [...preValue]
        return { ...prevItems }
      })
    } else {
      obj.config = {
        column: item.config.column,
        value: e
      }
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[item.type] = obj.config.value !== undefined ? [...preValue, obj] : [...preValue]

        return { ...prevItems }
      })
    }
  }

  const filterOption = (item: any, value: any) => {
    /* 聚合 */
    if (value && item.type === 'polymerize') {
      return (
        <ServerSelect
          placeholder={item.name}
          modelValue={searchValue.filters.polymerize.filter((it: any) => it.name === item.name) ?? []}
          options={Selectdata(value)}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 区域筛选 */
    if (item.type === 'pca') {
      return (
        <ServerAreaSelect
          placeholder={item.name}
          modelValue={searchValue.filters.pca.filter((it: any) => it.name === item.name) ?? []}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 园区筛选 */
    if (item.type === 'park') {
      return (
        <HsAdminSelecPark
          className="w-full"
          placeholder={item.name}
          mode="multiple"
          parklist={ParkList}
          value={searchValue.filters.park.filter((it: any) => it.name === item.name)?.[0]?.config?.values?.map((itt: any) => itt.value) ?? []}
          onChange={(_e: string, option: any) => {
            DataSelectsuccess(option, item)
          }}
        />
      )
    }

    /* 时间选择器 */
    if (item.type === 'date') {
      let value: any = null
      const theOne = searchValue.filters.date.find((it: any) => it.name === item.name)
      if (theOne) {
        let start = null
        let end = null
        if (theOne.config?.start?.value) {
          start = dayjs(theOne.config?.start?.value)
        }
        if (theOne.config?.end?.value) {
          end = dayjs(theOne.config?.end?.value)
        }
        value = [start, end]
      }
      return (
        <div className="">
          <RangePicker
            className="w-100%"
            value={value}
            onChange={(_date, datestr) => handleTimeRankonChange(datestr, item, 'date')}
            placeholder={['开始日期', '结束日期']}
          />
        </div>
      )
    }

    /** 时间选择器 时分秒 */
    if (item.type === 'time') {
      let value: any = null
      const theOne = searchValue.filters.time.find((it: any) => it.name === item.name)
      if (theOne) {
        let start = null
        let end = null
        if (theOne.config?.start?.value) {
          start = dayjs(theOne.config?.start?.value)
        }
        if (theOne.config?.end?.value) {
          end = dayjs(theOne.config?.end?.value)
        }
        value = [start, end]
      }
      return (
        <RangePicker
          value={value}
          showTime
          onChange={(_date, datestr) => handleTimeRankonChange(datestr, item, 'time')}
          placeholder={['开始日期', '结束日期']}
        />
      )
    }

    /* 火石产业筛选 */
    if (item.type === 'industry') {
      return (
        <ServerCascader
          placeholder={item.name}
          modelValue={searchValue.filters.industry.filter((it: any) => it.name === item.name) ?? []}
          type={'industry'}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 国民经济分类筛选 */
    if (item.type === 'national_economy_classification') {
      return (
        <ServerCascader
          placeholder={item.name}
          modelValue={searchValue.filters.national_economy_classification.filter((it: any) => it.name === item.name) ?? []}
          type={'national'}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 战略性新兴产业分类筛选 */
    if (item.type === 'strategic_industry') {
      return (
        <ServerCascader
          placeholder={item.name}
          modelValue={searchValue.filters.strategic_industry?.filter((it: any) => it.name === item.name) ?? []}
          type={'strategic_industry'}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 资质信息 */
    if (item.type === 'qualification') {
      const List: any = []
      searchValue.filters.qualification?.map((it: any) => {
        it.config.values.map((item: any) => {
          List.push(item.show)
        })
      })
      return (
        <TreeSelect
          showSearch={false}
          allowClear
          treeData={HonorTreeData}
          treeCheckable={true}
          style={{ width: '100%' }}
          placeholder={item.name}
          value={searchValue.filters.qualification?.filter((it: any) => it.name === item.name) ? List : []}
          onChange={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 最新市值(亿元) */
    if (item.type === 'number_range') {
      let value1: any = null
      let value2: any = null
      return (
        <div className="flex items-center">
          <InputNumber
            style={{ width: 200 }}
            placeholder={item.name}
            changeOnBlur
            controls={false}
            type="number"
            value={searchValue.filters.number_range?.filter((it: any) => it.name === item.name)[0]?.config?.start}
            onChange={(value: any) => {
              value1 = value
            }}
            onBlur={() => {
              number_onChange(
                item,
                'number_range',
                value1,
                searchValue.filters.number_range?.filter((it: any) => it.name === item.name)[0]?.config?.end
              )
            }}
          />
          ~
          <InputNumber
            style={{ width: 200 }}
            placeholder={item.name}
            controls={false}
            type="number"
            value={searchValue.filters.number_range?.filter((it: any) => it.name === item.name)[0]?.config?.end}
            onChange={(value: any) => {
              value2 = value
            }}
            onBlur={() => {
              number_onChange(
                item,
                'number_range',
                searchValue.filters.number_range?.filter((it: any) => it.name === item.name)[0]?.config?.start,
                value2
              )
            }}
          />
        </div>
      )
    }

    /* 是否条件筛选 */
    if (item.type === 'true_or_false') {
      return (
        <Select
          allowClear
          placeholder={item.name}
          className="w-100%"
          value={searchValue.filters.true_or_false?.filter((it: any) => it.name === item.name)[0]?.config?.value}
          onChange={(e: any) => DataSelectsuccess(e, item)}
          options={[
            { value: 0, label: '否' },
            { value: 1, label: '是' }
          ]}
        />
      )
    }
  }

  const number_onChange = (item: any, type: any, startValue: any, endValue: any) => {
    const newStart = startValue
    let newEnd = endValue

    if (newEnd && newStart > newEnd) {
      newEnd = null
    }
    const obj: any = {
      name: item.name,
      type: item.type,
      config: {
        column: item.config.column,
        start: newStart ?? null,
        end: newEnd ?? null
      }
    }

    setsearchValue((prevItems: any) => {
      const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
      prevItems.filters[type] = [obj, ...preValue]
      return { ...prevItems }
    })
  }

  //导出方法
  const setIsModalOpen = () => {
    if (selectedRowKeys.length > counts) {
      api.warning({
        message: '超过导出限制',
        description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
      })
      return
    }

    if (selectedRowKeys.length) {
      if (selectedRowKeys.length < 5000) EmailModalRef.current.showModal()
      if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) setModalOpen2(true)
      if (selectedRowKeys.length > 10000) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量限制10000条，请重新选择`
        })
      }
      if (selectedRowKeys.length > 500) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量500，请重新选择`
        })
      }
    } else {
      if (totalNumber > counts && counts !== 20000) {
        api.warning({
          message: '超过导出限制',
          description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
        })
      } else {
        if (totalNumber < 5000) EmailModalRef.current.showModal()
        if (totalNumber > 5000 && totalNumber < 10000) setModalOpen2(true)
        if (totalNumber > 10000) {
          api.warning({
            message: '超过导出限制',
            description: `导出超过单次数量限制10000条，请重新选择`
          })
        }
      }
    }
  }

  // 导出提交
  const handleExport = (obj: any) => {
    const params: any = {
      columns: [],
      filename: obj.filename,
      query: {
        release_item_id: release_item_id,
        ids: null,
        filters: {
          items: []
        },
        page: 1,
        page_size: 100
      }
    }
    columns.map((item: any) => {
      if (columnsStateMap[item.dataIndex]?.show) {
        params.columns.push({
          field: item.dataIndex,
          name: item.title
        })
      }
    })

    if (searchValue?.relation) {
      params.query.relation = searchValue?.relation
    } else {
      params.query.relation = null
    }

    if (selectedRowKeys?.length) {
      params.query.ids = selectedRowKeys
    } else {
      Object.keys(searchValue.filters).forEach((key) => params.query.filters.items.push(...searchValue.filters[key]))
      params.query.filters = params.query.filters.items
      params.query.keywords = inputValue ?? null
    }

    DataBasetexport(params).then((_res: any) => {
      let messages: any = `提交成功,请在${obj.Email}中查看导出结果`
      export_counts() //更新导出数量值
      if (selectedRowKeys.length) {
        if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      } else {
        if (totalNumber > 5000 && totalNumber < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      }
      message.success(messages)
      actionRef.current?.clearSelected()
      setselectedRowKeys([])
      setModalOpen2(false)
    })
  }

  //导出邮箱弹框确定
  const exportonok = () => {
    setModalOpen2(false)
    EmailModalRef.current.showModal()
  }

  const filters = (List: any[]) => {
    List = List.filter((item) => item.display_type !== 'not_display')
    const arr: any[] = []
    arr.push({
      title: '操作',
      dataIndex: 'operation',
      fixed: 'left',
      width: 100,
      render: (_: any, record: any) => (
        <Button
          type="link"
          onClick={() => {
            const true_or_false_list = List.filter((item: any) => item.display_type === 'true_or_false')
            const nameList = true_or_false_list.map((item: any) => item.name)
            for (const [key, value] of Object.entries(record)) {
              if (nameList.includes(key)) {
                record[key] = transformNormalNumberType(value as any) || record[key]
              }
            }
            showDetailModal(record, detailFieldList.current)
          }}>
          详情
        </Button>
      )
    })
    List.forEach((item: any) => {
      if (item.available) {
        const obj: any = {}
        obj.title = item.display_name || item.comment
        obj.dataIndex = item.name
        obj.queryable = item.queryable
        obj.width = 210
        // 火石产业
        if (obj.dataIndex === 'hs_ind_list') {
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { level_first: any }) => item.level_first))]
            return (
              <Popover
                content={
                  <div>
                    <p className="mb-2">火石产业分类：</p>
                    <HsAdminTable
                      columns={[
                        { title: '一级分类', dataIndex: 'level_first' },
                        { title: '二级分类', dataIndex: 'level_second' },
                        { title: '三级分类', dataIndex: 'level_third' },
                        { title: '四级分类', dataIndex: 'level_fourth' }
                      ]}
                      dataSource={text}
                      resizeable={false}
                      pagination={false}
                      scroll={{ y: 600 }}
                      className="w-160"
                    />
                  </div>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}个领域` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else if (obj.dataIndex === 'nea_ind_list') {
          // 国标行业分类
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { level_first: any }) => item.level_first))]

            return (
              <Popover
                content={
                  <div>
                    <p className="mb-2">国标行业分类：</p>
                    <HsAdminTable
                      columns={[
                        { title: '行业门类', dataIndex: 'level_first' },
                        { title: '行业大类', dataIndex: 'level_second' },
                        { title: '行业中类', dataIndex: 'level_third' },
                        { title: '行业细类', dataIndex: 'level_fourth' }
                      ]}
                      dataSource={text}
                      resizeable={false}
                      pagination={false}
                      rowKey={'end_code'}
                      scroll={{ y: 600 }}
                      className="w-160"
                    />
                  </div>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}个领域` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else if (obj.dataIndex === 'strategic_ind_list') {
          // 战新产业分类
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { level_first: any }) => item.level_first))]
            return (
              <Popover
                content={
                  <div>
                    <p className="mb-2">战新产业分类：</p>
                    <HsAdminTable
                      columns={[
                        { title: '一级分类', dataIndex: 'level_first' },
                        { title: '二级分类', dataIndex: 'level_second' },
                        { title: '三级分类', dataIndex: 'level_third' },
                        { title: '四级分类', dataIndex: 'level_fourth' }
                      ]}
                      dataSource={text}
                      resizeable={false}
                      pagination={false}
                      rowKey={'end_code'}
                      scroll={{ y: 600 }}
                      className="w-160"
                    />
                  </div>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}个领域` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else if (obj.dataIndex === 'carrier_list') {
          // 所属载体信息
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { carrier_name: any }) => item.carrier_name))]
            const items: any[] = []
            text.forEach((item: { type: any; carrier_level: any; carrier_name: any }) => {
              items.push({ key: '1', label: '载体类型', children: <span>{item.type || EMPTYTEXT}</span> })
              items.push({
                key: '2',
                label: '载体级别',
                children: <span>{item.carrier_level || EMPTYTEXT}</span>
              })
              items.push({ key: '3', label: '载体名称', children: <span>{item.carrier_name || EMPTYTEXT}</span>, span: 3 })
            })
            return (
              <Popover
                content={
                  <div>
                    <p className="mb-2">所属载体信息：</p>
                    <Descriptions title="" bordered column={2} items={items} />
                  </div>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}个园区` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else if (obj.dataIndex === 'qualified_list') {
          // 资质信息
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { name: any }) => item.name))]
            return (
              <Popover
                content={
                  <>
                    {text.map((item: any) => (
                      <p key={item.name}>{item.name}</p>
                    ))}
                  </>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}个资质` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else if (obj.dataIndex === 'org_info_list') {
          // 机构信息
          obj.render = (text: any) => {
            if (typeof text === 'string') {
              return <>{text}</>
            }
            const nameList = [...new Set(text.map((item: { company_name: any }) => item.company_name))]

            const items: any[] = []
            text.forEach((item: any) => {
              items.push({ key: '1', label: '机构类型', children: <span>{item.entity_type || EMPTYTEXT}</span> })
              items.push({
                key: '2',
                label: '机构名称',
                children: (
                  <Button type="link" onClick={() => openCompanyDetail(item.company_code)}>
                    {item.company_name}
                  </Button>
                )
              })
              items.push({
                key: '3',
                label: '所在区域',
                children: (
                  <span>
                    {item.province}
                    {item.city}
                    {item.area}
                  </span>
                ),
                span: 3
              })
            })
            return (
              <Popover
                content={
                  <div>
                    <p className="mb-2">机构信息：</p>
                    <Descriptions title="" bordered column={2} items={items} />
                  </div>
                }
                title=""
                trigger={'click'}>
                <Text className="cursor-pointer text-#0779ff" ellipsis={{ tooltip: false }}>
                  {nameList.length > 2 ? `${nameList[0]}等${nameList.length}家公司` : nameList.join('、')}
                </Text>
              </Popover>
            )
          }
        } else {
          if (item.display_type === 'true_or_false') {
            obj.render = (text: any, record: any) => {
              record[item.name] = transformNormalNumberType(text) || text
              return <>{record[item.name]}</>
            }
          } else {
            obj.render = (text: any) => {
              text = text && typeof text === 'object' ? JSON.stringify(text) : text
              return text?.length > 30 ? (
                <Tooltip title={typeof text === 'string' ? text : JSON.stringify(text)}>
                  <p className="truncate min-w-53">{typeof text === 'string' ? text : JSON.stringify(text)}</p>
                </Tooltip>
              ) : (
                <span>{text}</span>
              )
            }
          }
        }
        if (item.sort) {
          obj.sorter = true
          obj.sortDirections = ['descend', 'ascend']
        }
        arr.push(obj)
        if (!item.column_group?.name) {
          item.column_group ||= {}
          item.column_group.name = '默认分组'
        }
      }
    })
    let detailFieldNameGroup = List.map((item: { column_group: { name: any } }) => item.column_group?.name)
    detailFieldNameGroup = [...new Set(detailFieldNameGroup)]
    detailFieldList.current = detailFieldNameGroup.map((item: any) => ({
      label: item,
      value: item,
      children: []
    }))
    List.forEach((item: any) => {
      const _findItem: any = detailFieldList.current.find((ele: any) => ele.value === item.column_group?.name)
      if (_findItem) {
        _findItem.children.push({
          key: item.name,
          label: item.display_name || item.comment
        })
      }
    })
    return arr
  }

  //获取数据表头
  const Databasetitles = () => {
    if (!columnsChangeFlag) {
      return
    }
    Databasesort_ruleslist((res: any) => {
      //二维数组变成一维数组
      const sortlist = res.flat()
      Databasetitle(release_item_id).then((res: any) => {
        res = res.filter((item: { available: any }) => item.available)
        res.sort((a: { queryable: number }, b: { queryable: number }) => b.queryable - a.queryable)
        const obj: any = {
          action: {
            disable: true,
            show: true,
            sorter: true
          }
        }
        res.forEach((item: any, index: any) => {
          obj[item.name] = {
            show: item.queryable ? true : false,
            fixed: !index ? 'left' : false,
            ellipsis: !index ? true : false
          }
        })
        setColumnsStateMap(obj)

        res.forEach((item: any) => {
          sortlist.forEach((_item1: any) => {
            if (item.name === _item1.field) {
              item.sort = true
            }
          })
        })
        setColumns(filters(res))
      })
    })
  }

  //获取表头排序
  const Databasesort_ruleslist = async (callBack: any) => {
    const arr: any = []
    const list = await Databasesort_rules({ id: release_item_id, page: 1, page_size: 999 })
    list.items.forEach((item: any) => {
      if (item.type === 'time' || item.type === 'numeric') arr.push(item.config.fields)
    })
    callBack(arr)
  }

  const [totalNumber, settotalNumber] = useState(0)

  const [pagination, setPagination] = useImmer<any>({
    current: 1,
    pageSize: 50
  })

  const addPage = () => {
    if (pagination?.current * pagination.pageSize < totalNumber) {
      setPagination((prev: { current: number }) => {
        prev.current++
      })
      setcolumnsChangeFlag(false)
    }
    settotalNumber(0)
  }
  const minusPage = () => {
    setPagination((prev: { current: number }) => {
      prev.current--
    })
    setcolumnsChangeFlag(false)
  }

  //sorter 列表sort功能 sortOrder代表升序asc还是降序desc

  function sorterItem(e: any) {
    setsearchValue((prev: any) => {
      return {
        ...prev,
        sort: e
      }
    })
  }
  const sorter = (sortOrder: any) => {
    let sorttype = null
    if (sortOrder.order === 'ascend') sorttype = `${sortOrder.columnKey}:asc`
    if (sortOrder.order === 'descend') sorttype = `${sortOrder.columnKey}:desc`
    sorterItem(sorttype)
  }

  //获取列表数据
  const doRequest = () => {
    setloading(true)
    const params: any = {
      release_item_id: release_item_id,
      keywords: inputValue ?? null,
      filters: {
        items: []
      },
      sort: searchValue.sort
    }
    Object.keys(searchValue.filters).forEach((key) => params.filters.items.push(...searchValue.filters[key]))

    return DatabaseList({
      page: pagination.current,
      page_size: pagination.pageSize,
      id: params.release_item_id,
      keywords: params.keywords,
      filters: params.filters.items,
      ids: null,
      relation: null,
      sort: params.sort
    })
      .then((res) => {
        setloading(false)
        setData(
          res.items.map((item: any, index: number) => {
            Object.keys(item).forEach((key) => {
              handleTableShowDate(item, key)
            })
            return { ...item, index }
          })
        )
        settotalNumber(res.total)

        return res
      })
      .finally(() => {
        setloading(false)
      })
  }

  //清除所有筛选项
  const cleanSearchvalue = () => {
    setsearchValue((prevItems: any) => {
      return {
        ...prevItems,
        filters: {
          pca: [],
          polymerize: [],
          date: [],
          park: [],
          time: [],
          industry: [],
          national_economy_classification: [],
          strategic_industry: [],
          qualification: [],
          number_range: []
        }
      }
    })
    setinputValue('')
  }

  const getfiltersList = () => {
    // 获取筛选列表数据
    filtersList({ page: 1, page_size: 9999, id: release_item_id }).then((res: any) => {
      setfiltersitem(res.items)
      if (res.items.findIndex((its: any) => its.type === 'park') !== -1) {
        setParkList('true')
      }
    })
  }

  useEffect(() => {
    export_counts()
  }, [])

  useEffect(() => {
    if (release_item_id) {
      Databasetitles()
      getfiltersList()
      setsearchValue({
        ...searchValue,
        sort: null
      })
    }
  }, [release_item_id])

  useEffect(() => {
    doRequest()
    setcolumnsChangeFlag(true)
  }, [searchValue, pagination])

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal() {
          doRequest()
          Databasetitles()
        },
        getList() {
          doRequest()
        },
        //页面重置
        resizeTo() {
          setPagination((prevPagi: any) => {
            prevPagi.current = 1
            prevPagi.pageSize = 50
          })
        },
        resizeExport_counts() {
          export_counts()
        },
        clearsetselectedRowKeys() {
          setselectedRowKeys([])
        }
      }
    },
    [Inputsearch, searchValue]
  )
  const suffix = <SearchOutlined onClick={doRequest} className="suffix" /> //搜索图标
  const [inputValue, setinputValue]: any = useState('')
  return (
    <div className="w-100% h-85vh overflow-auto">
      <div className="bg-white">
        <div className="px-24px pt-24px">
          <span className="text-red font-bold text-18px">{release_item_name}</span>
          <div className="flex items-center pr-20px my-8px">
            <HsAdminInput
              className="w-290px Input"
              value={inputValue}
              placeholder="请输入关键词"
              suffix={suffix}
              onChange={(e: any) => setinputValue(e.target.value)}
              onPressEnter={doRequest}
            />
            <span className="text-blue-500 cursor-pointer ml-20px" onClick={() => cleanSearchvalue()}>
              重置
            </span>
          </div>
          <div className="flex flex-wrap">
            {filtersitem.map((item: any, _index: number) => {
              return (
                <div className="flex" key={_index}>
                  <span className="mt-5px mr-12px filterName w-106px">{item.name}:</span>
                  <div className="w-340px mr-10px mb-20px mr-24px">{filterOption(item, item.config.options)}</div>
                </div>
              )
            })}
          </div>
          <div className="flex items-center justify-between">
            <div className="mr-10px"></div>
            <div className="m-10px flex items-center ">
              <Popover
                arrow={false}
                content={
                  <div>
                    {contextHolder}
                    今日还能导出 <span className=""> {counts}</span>条
                  </div>
                }>
                <Button type="link" shape="round" onClick={setIsModalOpen}>
                  <DownloadOutlined className="w-12px mr-2" />
                  {selectedRowKeys.length ? `导出(${selectedRowKeys.length})` : '导出excel'}
                </Button>
              </Popover>
            </div>
          </div>
        </div>
        {loading && <HsAdminSpin />}
        <HsAdminProTable
          id="RelationList-table"
          columns={columns}
          rowKey="id"
          dataSource={data}
          onChange={(_a: any, _b: any, sortOrder: any) => sorter(sortOrder)}
          columnsState={{ value: columnsStateMap, onChange: setColumnsStateMap }}
          pagination={false}
          scroll={{ x: 1500, y: 500 }}
          options={{ density: false, setting: false }}
        />
        <div className="flex items-center justify-end py-15px mr-20px">
          <div className="mr-10px">{`共${totalNumber}`}条</div>
          <Button className="mr-10px" type="primary" onClick={minusPage} disabled={pagination.current === 1}>
            上一页
          </Button>
          <div className="mr-20px">{`${(pagination.current - 1) * pagination.pageSize + 1} - ${pagination.current * pagination.pageSize}`}条</div>
          <Button type="primary" onClick={addPage} disabled={pagination.current * pagination.pageSize >= totalNumber}>
            下一页
          </Button>
        </div>
      </div>

      <ServerEmailModal ref={EmailModalRef} success={handleExport} title={'导出数据'}></ServerEmailModal>
      <Modal
        title={'单次导出超出5000条，需要通过审批才能导出，是否继续？'}
        open={isModalOpen2}
        onCancel={() => setModalOpen2(false)}
        onOk={exportonok}></Modal>
      {Detail}
    </div>
  )
}
export default memo(forwardRef(RelationList))
